package utils

import (
	"sync"
)

type void struct{}

var member void

type IData interface{}

type Set struct {
	mapset map[IData]struct{}
	mutex  sync.Mutex
}

func NewSet() *Set {
	return &Set{
		mapset: make(map[IData]struct{}),
		mutex:  sync.Mutex{},
	}
}

func (s *Set) Add(data IData) bool {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	s.mapset[data] = member
	return true
}

func (s *Set) Remove(data IData) {
	defer s.mutex.Unlock()
	s.mutex.Lock()
	for k, _ := range s.mapset {
		if k == data {
			delete(s.mapset, k)
			return
		}
	}
}

func (s *Set) Pop() IData {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if len(s.mapset) <= 0 {
		return nil
	}
	for k, _ := range s.mapset {
		return s.mapset[k]
	}
	return nil
}

func (s *Set) Check(data IData) bool {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	_, ok := s.mapset[data]
	return ok
}

func (s *Set) Size() int {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	return len(s.mapset)

}

func (s *Set) All() []IData {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	datas := make([]IData, 0)
	for k, _ := range s.mapset {
		datas = append(datas, k)
	}
	return datas
}
